package com.cuckoo.mall.thus.order.addorder;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bgn.baseframe.base.MVPBaseActivity;
import com.bgn.baseframe.network.HttpObserver;
import com.bgn.baseframe.network.bean.TDataBean;
import com.bgn.baseframe.utils.BaseStringUtil;
import com.bgn.baseframe.utils.KeyboardHelper;
import com.bgn.baseframe.utils.ToastUtil;
import com.bgn.baseframe.utils.UiUtil;
import com.bgn.baseframe.utils.evenbus.MainEvent;
import com.bgn.baseframe.utils.jsontool.GsonUtil;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cuckoo.mall.R;
import com.cuckoo.mall.javabean.CartProductItem;
import com.cuckoo.mall.javabean.CreateOrderParms;
import com.cuckoo.mall.javabean.OrderResult;
import com.cuckoo.mall.javabean.PostAddress;
import com.cuckoo.mall.javabean.Ticket;
import com.cuckoo.mall.network.ApiManager;
import com.cuckoo.mall.thus.order.adapter.OrderProductAdapter;
import com.cuckoo.mall.thus.utils.DialogHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */
@Route(path = "/mall/addOrderFromCartActivity", group = "mall")
public class AddOrderFromCartActivity extends MVPBaseActivity<AddorderContract.View, AddorderPresenter> implements AddorderContract.View {

    @BindView(R.id.tv_order_name)
    TextView tvOrderName;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.tv_order_phone)
    TextView tvOrderPhone;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_order_address)
    TextView tvOrderAddress;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_remark_count)
    TextView tvRemarkCount;
    @BindView(R.id.check_pay)
    CheckBox checkPay;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.tv_province)
    TextView tvProvince;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_p_c_label)
    TextView tv_p_c_label;
    /*底部三个价格*/
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.tv_order_price)
    TextView tv_order_price;
    @BindView(R.id.tv_ticket)
    TextView tvTicket;
    /*底部三个价格*/
    /*商品数据模块*/
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    private OrderProductAdapter orderProductAdapter;
    private List<CartProductItem> products = new ArrayList<>();
    /*订单数据提交*/ CreateOrderParms parms;
    private int coupon_id = 0;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_submit_order);
        //AndroidBug5497Workaround.assistActivity(getActivity());
        ButterKnife.bind(this);
        getTitleBar().setTitle(R.string.order_info);
        if (getIntent() != null && !TextUtils.isEmpty(getIntent().getStringExtra(DATASTRING))) {
            String data = getIntent().getStringExtra(DATASTRING);
            List<CartProductItem> dataItems = GsonUtil.fromJsonList(data, CartProductItem.class);
            if (dataItems != null && dataItems.size() > 0) {
                products.addAll(dataItems);
                initView();
            } else {
                finish();
            }
        } else {
            finish();
        }
    }

    private void initView() {
        initBaseInfoView();
        initRecycleView();
        mPresenter.checkTicketInfo();
    }

    private void initRecycleView() {
        orderProductAdapter = new OrderProductAdapter(products);
        recycleView.setAdapter(orderProductAdapter);
        /*消除滑动卡顿*/
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        linearLayoutManager.setAutoMeasureEnabled(true);
        recycleView.setLayoutManager(linearLayoutManager);
        recycleView.setHasFixedSize(true);
        recycleView.setNestedScrollingEnabled(false);
        /*消除滑动卡顿*/
        orderProductAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //  ARouter.getInstance().build("/mall/goodMultipleDetailActivity").withString(ID, products.get(position).getProduct_info().getProduct_id()).navigation();
            }
        });
    }

    int total_sub = 0;

    private void initBaseInfoView() {
        tvOrderName.setText(Html.fromHtml(tvOrderName.getText() + "<font color=#ff0000>" + "*" + "</font>"));
        tvOrderPhone.setText(Html.fromHtml(tvOrderPhone.getText() + "<font color=#ff0000>" + "*" + "</font>"));
        tvOrderAddress.setText(Html.fromHtml(tvOrderAddress.getText() + "<font color=#ff0000>" + "*" + "</font>"));
        tvRemarkCount.setText(Html.fromHtml("<font color=#FF0000>" + 0 + "</font>" + "/150  " + UiUtil.getString(R.string.zhi)));
        tv_p_c_label.setText(Html.fromHtml(tv_p_c_label.getText() + "<font color=#ff0000>" + "*" + "</font>"));
        for (CartProductItem items : products) {
            if (items.getProduct_info() != null) {
                total_sub += items.getProduct_info().getPrice() * items.getNumber();
            }
        }
        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(etCode.getText().toString()) && etCode.getText().toString().length() == 5) {
                    ApiManager.getAddressByCode(etCode.getText().toString()).subscribe(new HttpObserver<TDataBean<PostAddress>>(AddOrderFromCartActivity.this) {
                        @Override
                        public void onSucceed(TDataBean<PostAddress> value) {
                            tvProvince.setText(value.getData().getProvince());
                            tvCity.setText(value.getData().getCity());
                            isSelected = true;
                        }

                        @Override
                        public void onDefeat(TDataBean<PostAddress> value) {
                            // super.onDefeat(value);
                            //ToastUtil.showInfo("未查询到该邮编");
                        }

                        @Override
                        public void onError(Throwable e) {
//                            super.onError(e);
                        }
                    });
                }

            }
        });
        tvPrice.setText(products.get(0).getProduct_info().getCurrency() + " " + BaseStringUtil.getPrioceFormatString(total_sub));
        tvTotalPrice.setText(products.get(0).getProduct_info().getCurrency() + " " + BaseStringUtil.getPrioceFormatString(total_sub));
        tv_order_price.setText(products.get(0).getProduct_info().getCurrency() + " " + BaseStringUtil.getPrioceFormatString(total_sub));
        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int counts = etRemark.getText().length();
                tvRemarkCount.setText(Html.fromHtml("<font color=#FF0000>" + counts + "</font>" + "/150  " + UiUtil.getString(R.string.zhi)));
            }
        });
    }

    OptionsPickerView pickerView;
    private boolean isSelected = false;

    @OnClick({R.id.tv_province, R.id.tv_city, R.id.tv_price, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_province:
            case R.id.tv_city:
                if (pickerView == null) {
                    pickerView = DialogHelper.showAddressPickWheel(getActivity(), new DialogHelper.PickCallBack() {
                        @Override
                        public void whenSelected(int p1, int p2, String s1, String s2) {
                            tvProvince.setText(s1);
                            tvCity.setText(s2);
                            isSelected = true;
                        }
                    });
                    KeyboardHelper.hideKeyboard(tvCity);
                } else {
                    KeyboardHelper.hideKeyboard(tvCity);
                    pickerView.show();
                }
                break;
            case R.id.tv_price:
                break;
            case R.id.tv_submit:

                if (checkData() && isNetworkerConnectHint()) {
                    showLoadingView();
                    mPresenter.createOrder(parms);
                }

                break;
        }
    }

    private boolean checkData() {
        boolean isDataOk = true;
        String name = etName.getText().toString().trim();//姓名2-40个字符
        String phone = etPhone.getText().toString();//手机号码7-15个数字
        String code = etCode.getText().toString();
        String address = etAddress.getText().toString().trim();//详细地址2-70个字符
        String email = etEmail.getText().toString();//请输入有效的邮箱
        String remark = etRemark.getText().toString().trim();
        String province = tvProvince.getText().toString();//请选择省份、市区
        String city = tvCity.getText().toString();//请选择付款方式

        if (TextUtils.isEmpty(name)) {
            isDataOk = false;
            ToastUtil.showInfo(getString(R.string.order_name_rule));
        } else if (name.length() < 2 || name.length() > 40) {
            isDataOk = false;
            ToastUtil.showInfo(getString(R.string.order_name_rule2));
        } else if (TextUtils.isEmpty(phone)) {
            isDataOk = false;
            ToastUtil.showInfo(getString(R.string.order_phone_rule));
        } else if (phone.length() < 7 || phone.length() > 15) {
            isDataOk = false;
            ToastUtil.showInfo(getString(R.string.order_phone_rule2));
        } else if (!isSelected) {
            isDataOk = false;
            ToastUtil.showInfo(getString(R.string.order_p_c_rule));
        } else if (TextUtils.isEmpty(address)) {
            isDataOk = false;
            ToastUtil.showInfo(getString(R.string.order_address_rule));
        } else if (!TextUtils.isEmpty(email) && !BaseStringUtil.isValidEmail(email)) {
            isDataOk = false;
            ToastUtil.showInfo(getString(R.string.order_email_rule));
        } else if (!checkPay.isChecked()) {
            isDataOk = false;
            ToastUtil.showInfo(getString(R.string.order_pay_rule));
        } else {
            parms = new CreateOrderParms();
            parms.setName(name);
            parms.setPhone(phone);
            parms.setZip_code(code);
            parms.setAddress(address);
            parms.setEmail(email);
            parms.setRemarks(remark);
            parms.setProvince(province);
            parms.setCity(city);
            parms.setCart_ids(getCartIdsString());
            parms.setCoupon_id(coupon_id);
        }
        return isDataOk;
    }

    @Override
    public void onBackPressed() {
//        DialogHelper.showConfirmDialog(getActivity(), getString(R.string.sure_cancle_order), getString(R.string.sure_ok), getString(R.string.think_again), new DialogHelper.DialogPressCallBack() {
//            @Override
//            public void whenPressRightButton() {
//                finish();
//            }
//        });
        finish();
    }

    @Override
    public void whenCreateOrderSucceed(OrderResult reslut) {
        EventBus.getDefault().post(new MainEvent(MainEvent.UPDATE_CART));
        String dataString = GsonUtil.toJson(reslut);
        ARouter.getInstance().build("/mall/addOrderSucceedActivity").withString(DATASTRING, dataString).navigation();
        finish();
    }

    @Override
    public void whenGetTicketInfo(Ticket ticket) {
        if (ticket != null) {
            total_sub = total_sub - ticket.getMoney();
            if (total_sub < 0) {
                total_sub = 0;
            }
            tvTicket.setText("-" + ticket.getCurrency() + " " + BaseStringUtil.getPrioceFormatString(ticket.getMoney()));
            tvPrice.setText(products.get(0).getProduct_info().getCurrency() + " " + BaseStringUtil.getPrioceFormatString(total_sub));
            tv_order_price.setText(products.get(0).getProduct_info().getCurrency() + " " + BaseStringUtil.getPrioceFormatString(total_sub));
            coupon_id = ticket.getId();
        }
    }

    private String getCartIdsString() {
        String idsString = "";
        for (CartProductItem item : products) {
            idsString = idsString + item.getCart_id() + ",";
        }
        if (!TextUtils.isEmpty(idsString)) {
            idsString = idsString.substring(0, idsString.length() - 1);
        }
        return idsString;
    }
}
